package com.panopset.sf;

import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;

/**
 * Full screen window. Esc key always disposes it. Usually you would add an
 * animated panel, such as a com.panopset.gui.Osgw panel, using getFrame().
 * 
 * Override load and save methods to load and save state, as needed.
 * 
 * @author Karl Dinwiddie
 * 
 */
public abstract class FullScreenWindow {

	/**
	 * Off screen graphics world.
	 */
	private final Osgw orz;

	/**
	 * Paint cycle.
	 * 
	 * @param g
	 *            Graphics.
	 */
	public abstract void paintCycle(Graphics2D g);

	/**
	 * Graphics environment.
	 */
	private final GraphicsEnvironment ge = GraphicsEnvironment
			.getLocalGraphicsEnvironment();

	/**
	 * Graphics device.
	 */
	private final GraphicsDevice gd = ge.getDefaultScreenDevice();

	/**
	 * Full screen window frame.
	 */
	private final JFrame frame;

	/**
	 * @return Full screen window frame.
	 */
	public final JFrame getFrame() {
		return frame;
	}

	/**
	 * Constructor.
	 */
	public FullScreenWindow() {
		frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setUndecorated(true);
		frame.setAlwaysOnTop(true);
		frame.setSize(Toolkit.getDefaultToolkit().getScreenSize());
		frame.setLocation(0, 0);
		orz = new Osgw(frame.getSize()) {

			@Override
			public void paintCycle(final Graphics2D g) {
				FullScreenWindow.this.paintCycle(g);
			}

		};
		frame.add(orz.getPanel());
	}

	/**
	 * Override as needed to load state.
	 */
	protected void load() {
	}

	/**
	 * Override as needed to save state.
	 */
	protected void save() {
	}

	/**
	 * Load state and show the full screen window.
	 */
	public final void show() {
		load();
		frame.setVisible(true);
		gd.setFullScreenWindow(frame);
		frame.addKeyListener(new KeyAdapter() {
			public void keyPressed(final KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
					quit();
				}
			}
		});
	}

	/**
	 * Dispose the full screen window and save state.
	 */
	public final void quit() {
		save();
		gd.setFullScreenWindow(null);
		frame.dispose();
	}

	/**
	 * @return Width.
	 */
	public final int getWidth() {
		return orz.getWidth();
	}

	/**
	 * @return Height.
	 */
	public final int getHeight() {
		return orz.getHeight();
	}
}
